package com.xiaoma.tpo.dao;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.xiaoma.tpo.baseDao.BaseDaoImpl;
import com.xiaoma.tpo.baseDao.DefaultRowMapper;
import com.xiaoma.tpo.domain.UserListening;
import com.xiaoma.tpo.dto.TopListeningVo;

@Repository
public class UserListeningDao extends BaseDaoImpl<UserListening>{

    private static final Logger LOG = LoggerFactory.getLogger(UserListeningDao.class);
    
    @SuppressWarnings("unchecked")
    public List<UserListening> orderByListeningCount(String date) {
        String sql = "SELECT * FROM user_listening where date = ? ORDER BY listening_count desc";
        LOG.info("SQL:{}; date={}", sql, date);
        List<?> result = jdbcTemplate.query(sql, new DefaultRowMapper(UserListening.class, getNameHandler()), date);
        return (List<UserListening>)result;
    }
    
    @SuppressWarnings("unchecked")
    public List<TopListeningVo> getTopListenings(String date, int count) {
        String sql = "SELECT b.name, b.avatar, a.listening_count, null as ranking FROM user_listening a left join user b on a.user_id = b.id where a.date = ? order by a.listening_count desc limit ?";
        LOG.info("SQL:{}; date={}; count={}", sql, date, count);
        List<?> result = jdbcTemplate.query(sql, new DefaultRowMapper(TopListeningVo.class, getNameHandler()), date, count);
        return (List<TopListeningVo>)result;
    }
    
    public int getUserTotalListeningCount(int userId) {
        String sql = "select sum(total_count) from user_listening where user_id = ?";
        LOG.info("SQL:{}; userId={};", sql, userId);
        return jdbcTemplate.queryForInt(sql, userId);
    }
    
}
